const {app, BrowserWindow, desktopCapturer, ipcMain, Menu} = require('electron')
const path = require('path')

const websocketUtil = require("./src/components/websocket/WebSocketUtil");
const {
    ws_selectDeviceList,
    ws_deleteDevice,
    ws_insertDevice,
    ws_updateDevice
} = require("./src/components/sqlite3/DB_system_ws");
const {
    ws_msg_deleteMsg,
    ws_msg_insertMsg,
    ws_msg_selectMsgList,
    ws_msg_updateMsg
} = require("./src/components/sqlite3/DB_system_ws_msg");
const url = require("node:url");

let mainWindow
let availableScreens
const websocketMap = new Map()
let selectedWebsocket
// TODO 创建窗口方法
function createWindow() {

    // TODO 设置屏幕尺寸，加载preload文件
    mainWindow = new BrowserWindow({
        width: 900,
        height: 600,
        frame: true,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'), // 正确的路径
        },
    });

    // TODO 主线程  监听事件，设置窗口尺寸
    ipcMain.on('set-size', (event, size) => {
        const {width, height} = size
        try {
            mainWindow.setSize(width, height, true)
        } catch (e) {
            console.log(e)
        }
    })


    // TODO 主线程 监听事件 首次连接 发送websocket数据
    ipcMain.handle('login', async () => {

        try {
            let data = await websocketUtil.invoke('login', null, 'logined');
            return data;
        } catch (error) {
            console.error('Error during login:', error);
        }
    });

    ipcMain.handle('logout', async () => {
        try {
            let data = await websocketUtil.disconnect('logout', null, 'logouted');
            return data;
        } catch (error) {
            console.log('Error during disconnect')
        }
    })

    ipcMain.handle('connect', async () => {
        try {
            let data = await websocketUtil.connect('connect', null, 'connected');
            return data;
        } catch (error) {
            console.log('Error during connect', error)
        }
    })

    // TODO 主线程 监听事件 发起远程控制请求，携带remoteCode
    ipcMain.handle('control', async (event, data) => {
        try {
            websocketUtil.sendData(data)
        } catch (e) {
            console.log(e)
        }
    })

    // TODO 主线程 监听事件 puppet、control共享的信道，就是转发
    ipcMain.on('forward', (event, data) => {
        try {
            console.log('websocket send data')
            console.log('data:', data)
            websocketUtil.sendData(data);
        } catch (e) {
            console.log(e)
        }
    })


    ipcMain.handle('ws-select-device-list', async (event, data) => {
        try {
            return await ws_selectDeviceList()
        } catch (e) {
            console.log(e)
        }
    })
    ipcMain.handle('ws-insert-device', async (event, data) => {
        try {
            return await ws_insertDevice(data)
        } catch (e) {
            console.log(e)
        }
    })
    ipcMain.handle('ws-update-device', async (event, data) => {
        try {
            return await ws_updateDevice(data)
        } catch (e) {
            console.log(e)
        }
    })
    ipcMain.handle('ws-delete-device', async (event, data) => {
        try {
            return await ws_deleteDevice(data)
        } catch (e) {
            console.log(e)
        }
    })


    ipcMain.handle('ws-msg-select-msg-list', async (event, data) => {
        try {
            return await ws_msg_selectMsgList(data)
        } catch (e) {
            console.log(e)
        }
    })


    ipcMain.handle('ws-msg-delete-msg', async (event, data) => {
        try {
            return await ws_msg_deleteMsg(data)
        } catch (e) {
            console.log(e)
        }
    })
    ipcMain.handle('ws-msg-insert-msg', async (event, data) => {
        try {
            console.log(typeof selectedWebsocket)
            selectedWebsocket.sendData(data)
            return await ws_msg_insertMsg(data)
        } catch (e) {
            console.log(e)
        }
    })
    ipcMain.handle('ws-msg-update-msg', async (event, data) => {
        try {
            return await ws_msg_updateMsg(data)
        } catch (e) {
            console.log(e)
        }
    })


    ipcMain.handle('change-websocket', async (event, data) => {
        try {
            const client = new websocketUtil(data.url)
            await client.connect();
            websocketMap.set(url, client)
            initData(client)
            selectedWebsocket = client
            // selectedWebsocket.disconnect()
            return true
        } catch (e){
            console.log(e)
            return false
        }
    })


    // TODO 加载页面路径
    mainWindow.loadURL('http://localhost:3000/');
    mainWindow.setMenu(null)

    // TODO 当点击关闭按钮时
    mainWindow.on('closed', function () {
        mainWindow = null
    })

    // TODO 当准备呈现页面时
    mainWindow.once('ready-to-show', () => {
        mainWindow.show()
        // 定时更新屏幕数据
        setInterval(freshScreen, 3000)
    })


    // TODO 打开开发工具
    mainWindow.webContents.openDevTools()

}

// TODO 对外暴露方法  用于渲染进程调用
function send(channel, ...args) {
    mainWindow.webContents.send(channel, ...args)
}

// 更新屏幕数据
const freshScreen = () => {
    desktopCapturer.getSources({
        types: ['screen']
    }).then(sources => {
        availableScreens = sources
        sendScreenInfo(sources)
    })
}

const initData = (websocketUtil) => {
    // TODO websocket 接收到controlled事件
    websocketUtil.on('controlled', (data) => {
        mainWindow.webContents.send('control-state', data.data.remoteCode, 1)
    })

    websocketUtil.on('be-controlled', (data) => {
        mainWindow.webContents.send('control-state', data.fromCode, 2)
    })


    websocketUtil.on('offer', (data) => {
        console.log('main.js offer')
        mainWindow.webContents.send('offer', data.data.sdp.toString())
    })

    websocketUtil.on('answer', (data) => {
        console.log('main.js answer')
        console.log('answer', data.data.sdp.toString())
        mainWindow.webContents.send('answer', data.data.sdp.toString())
    })

    websocketUtil.on('slave-candidate', (data) => {
        console.log('main.js slave-candidate')
        console.log(data)
        mainWindow.webContents.send('slave-candidate', data)
    })

    websocketUtil.on('master-candidate', (data) => {
        console.log('main.js master-candidate')
        console.log(data)
        mainWindow.webContents.send('master-candidate', data)
    })
}


// 主线程数据发往其他线程
const sendScreenInfo = (screenList) => {
    mainWindow.webContents.send('screen-info', screenList)
}

app.on('ready', function () {
    createWindow()
})



